package com.ocom.aiotweb.aspect;

import com.alibaba.fastjson.JSONObject;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.utils.ResultUtil;
import com.ocom.security.authentication.YoCiUser;
import com.ocom.security.utils.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;

@Aspect
@Component
public class ServiceAspect {

    private Logger log = LoggerFactory.getLogger(ServiceAspect.class);

    //切入点
    @Around("execution(* com.ocom.aiotweb.controller.*.*(..))")
    public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {

        // 类名
        String className = pjp.getTarget().getClass().getName();
        //方法名
        String methodName = pjp.getSignature().getName();

        try {
            Object[] args = pjp.getArgs();

            JSONObject jsonObject= null;
            try {
                for (int i = 0; i < args.length; i++) {
                    Object object=args[i];
                    if (object instanceof HttpServletRequest || object instanceof HttpServletResponse) {
                        continue;
                    }
                    jsonObject=JSONObject.parseObject(JSONObject.toJSONString(object));
                }
            }catch (Exception exception){

            }
            String ip = "";
            try {
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                ip = request.getRemoteAddr();;
            }catch (Exception exception){

            }

            Object re = pjp.proceed(args);

            YoCiUser yoCiUser =new YoCiUser("未知",new ArrayList<>(),new ArrayList<>());
            try {
                yoCiUser = SecurityUtils.getYoCiUser();
            }catch (Exception e){
                
            }
            if(yoCiUser!=null && !methodName.contains("OnShow") && !methodName.equals("otaFileList")
                    && !methodName.equals("getOtaList")){
                log.info("【系统日志】【aiotweb】管理员【{}】ip【{}】控制器【{}】方法【{}】参数【{}】返回【{}】",yoCiUser.getId(),ip,className,methodName,jsonObject,re);
            }

            return re;
        }catch (Exception e){
            log.info("请求URL:,切面异常:【{}】",e);
            return ResultUtil.error(ResultEnum.Err_4014);
        }
    }



}
